<template>
  <div class="app-container">
    <!-- 顶部标题和筛选 -->
    <el-card class="header-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <el-select v-model="selectedFactory" placeholder="请选择水厂" style="width: 100%" @change="handleFactoryChange">
            <el-option v-for="factory in factoryOptions" :key="factory.dictValue" :label="factory.dictLabel"
              :value="factory.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="12">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"
            @change="handleDateChange" />
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 主要统计指标 -->
    <el-row :gutter="20" class="metric-row">
      <!-- 水质统计 -->
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="card-header">
            <h3 class="card-title">水质统计</h3>
            <span class="card-date">{{ currentDate }}</span>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">pH值</span>
              <span class="metric-range">(6.5-8.5)</span>
            </div>
            <div class="metric-value">{{ waterQualityData.ph || '--' }}</div>
            <div class="metric-footer">
              <span class="metric-status" :class="getStatusClass(waterQualityData.phResult)">
                {{ waterQualityData.phResult || '--' }}
              </span>
            </div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">浊度(NTU)</span>
              <span class="metric-range">(≤1.0)</span>
            </div>
            <div class="metric-value">{{ waterQualityData.turbidity || '--' }}</div>
            <div class="metric-footer">
              <span class="metric-status" :class="getStatusClass(waterQualityData.turbidityResult)">
                {{ waterQualityData.turbidityResult || '--' }}
              </span>
            </div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">余氯(mg/L)</span>
              <span class="metric-range">(0.3-0.5)</span>
            </div>
            <div class="metric-value">{{ waterQualityData.residualChlorine || '--' }}</div>
            <div class="metric-footer">
              <span class="metric-status" :class="getStatusClass(waterQualityData.residualChlorineResult)">
                {{ waterQualityData.residualChlorineResult || '--' }}
              </span>
            </div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">达标率</span>
            </div>
            <div class="metric-value">{{ waterQualityStandardRate.qualifiedRate || '--' }}%</div>
            <div class="metric-footer">
              <span class="metric-status"
                :class="waterQualityStandardRate.qualifiedRate >= 95 ? 'status-good' : 'status-warning'">
                {{ waterQualityStandardRate.qualifiedRate >= 95 ? '优秀' : '需改进' }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 供水统计 -->
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="card-header">
            <h3 class="card-title">供水统计</h3>
            <span class="card-date">{{ currentDate }}</span>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">日供水量(m³)</span>
              <span class="metric-trend"
                :class="supplyData.dailySupplyChangeRate?.startsWith('+') ? 'trend-up' : 'trend-down'">
                {{ supplyData.dailySupplyChangeRate || '--' }}
              </span>
            </div>
            <div class="metric-value">{{ formatNumber(supplyData.dailySupplyVolume) || '--' }}</div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">累计供水量(m³)</span>
              <span class="metric-trend"
                :class="supplyData.totalSupplyChangeRate?.startsWith('+') ? 'trend-up' : 'trend-down'">
                {{ supplyData.totalSupplyChangeRate || '--' }}
              </span>
            </div>
            <div class="metric-value">{{ formatNumber(supplyData.totalSupplyVolume) || '--' }}</div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">供水压力(MPa)</span>
            </div>
            <div class="metric-value">{{ supplyData.supplyPressure || '--' }}</div>
            <div class="metric-footer">
              <span class="metric-status" :class="getPressureStatusClass(supplyData.pressureStatus)">
                {{ supplyData.pressureStatus || '--' }}
              </span>
            </div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">产能利用率</span>
            </div>
            <div class="metric-value">{{ capacityUtilizationRate || '--' }}%</div>
            <div class="metric-footer">
              <span class="metric-status" :class="capacityUtilizationRate >= 85 ? 'status-good' : 'status-warning'">
                {{ capacityUtilizationRate >= 85 ? '高效' : '需提升' }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 成本统计 -->
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="card-header">
            <h3 class="card-title">成本统计</h3>
            <span class="card-date">{{ currentDate }}</span>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">单位成本(元/m³)</span>
              <span class="metric-trend"
                :class="costData.unitCostChangeRate?.startsWith('+') ? 'trend-up' : 'trend-down'">
                {{ costData.unitCostChangeRate || '--' }}
              </span>
            </div>
            <div class="metric-value">{{ costData.unitCost || '--' }}</div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">药剂成本(万元)</span>
              <span class="metric-trend"
                :class="costData.chemicalCostChangeRate?.startsWith('+') ? 'trend-up' : 'trend-down'">
                {{ costData.chemicalCostChangeRate || '--' }}
              </span>
            </div>
            <div class="metric-value">{{ costData.chemicalCost || '--' }}</div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">能耗成本(万元)</span>
              <span class="metric-trend"
                :class="costData.energyCostChangeRate?.startsWith('+') ? 'trend-up' : 'trend-down'">
                {{ costData.energyCostChangeRate || '--' }}
              </span>
            </div>
            <div class="metric-value">{{ costData.energyCost || '--' }}</div>
          </div>

          <div class="metric-item">
            <div class="metric-header">
              <span class="metric-title">成本节约率</span>
            </div>
            <div class="metric-value">{{ costSavingRate || '--' }}%</div>
            <div class="metric-footer">
              <span class="metric-status" :class="costSavingRate >= 10 ? 'status-good' : 'status-warning'">
                {{ costSavingRate >= 10 ? '优秀' : '需改进' }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 待办任务 -->
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="card-header">
            <h3 class="card-title">待办任务</h3>
            <span class="card-date">{{ currentDate }}</span>
          </div>

          <div v-for="(task, index) in todoTasks" :key="index" class="task-item">
            <div class="task-header">
              <span class="task-title">{{ task.taskName }}</span>
              <el-tag :type="getTaskTagType(task.status)" size="small">
                {{ task.status }}
              </el-tag>
            </div>
            <div class="task-time">{{ task.lastUpdateDesc }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表分析区域 -->
    <el-card class="chart-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="水质指标" name="waterQuality">
          <el-row :gutter="20" v-if="activeTab === 'waterQuality'">
            <el-col :span="12">
              <ECharts :option="waterQualityTrendOption" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :option="waterQualityStandardOption" height="300px" />
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="生产指标" name="production">
          <el-row :gutter="20" v-if="activeTab == 'production'">
            <el-col :span="12">
              <ECharts :option="supplyTrendOption" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :option="capacityUtilizationOption" height="300px" />
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="成本指标" name="cost">
          <el-row :gutter="20" v-if="activeTab == 'cost'">
            <el-col :span="12">
              <ECharts :option="costCompositionOption" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :option="unitCostComparisonOption" height="300px" />
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="设备指标" name="equipment">
          <el-row :gutter="20" v-if="activeTab == 'equipment'">
            <el-col :span="12">
              <ECharts :option="equipmentStatusOption" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :option="failureRateTrendOption" height="300px" />
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="工单指标" name="workOrder">
          <el-row :gutter="20" v-if="activeTab == 'workOrder'">
            <el-col :span="12">
              <ECharts :option="workOrderEfficiencyOption" height="300px" />
            </el-col>
            <el-col :span="12">
              <ECharts :option="workOrderCompletionOption" height="300px" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import ECharts from '@/components/ECharts/index.vue'
import {
  getFactoryList,
  getEquipmentStatus,
  getWaterQualityStatistics,
  getFailureRateTrend,
  getSupplyStatistics,
  getWorkOrderEfficiency,
  getCostStatistics,
  getWorkOrderCompletionRate,
  getTodoTasks,
  getWaterQualityIndex,
  getWaterQualityStandardRate,
  getTargetTrend,
  getCapacityUtilization,
  getCostComposition,
  getUnitCostComparison
} from '@/api/prod_operate/kpi'

// 当前日期
const currentDate = ref(new Date().toLocaleDateString())

// 水厂选项
const factoryOptions = ref([])
const selectedFactory = ref('')

// 日期范围
const dateRange = ref([
  new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().split('T')[0],
  new Date().toISOString().split('T')[0]
])

// 活动标签页
const activeTab = ref('waterQuality')

// 数据状态
const loading = ref(false)

// 各模块数据
const waterQualityData = reactive({})
const waterQualityStandardRate = reactive({})
const supplyData = reactive({})
const costData = reactive({})
const todoTasks = ref([])
const equipmentStatus = reactive({})
const failureRateTrend = reactive({})
const workOrderEfficiency = reactive({})
const workOrderCompletionRate = reactive({})
const targetTrend = reactive({})
const capacityUtilization = reactive({})
const costComposition = reactive({})
const unitCostComparison = reactive({})

// 计算属性
const capacityUtilizationRate = computed(() => {
  if (!capacityUtilization.actualCapacity || !capacityUtilization.designedCapacity) return 0
  const actual = capacityUtilization.actualCapacity.reduce((a, b) => a + b, 0)
  const designed = capacityUtilization.designedCapacity.reduce((a, b) => a + b, 0)
  return designed ? Math.round((actual / designed) * 100) : 0
})

const costSavingRate = computed(() => {
  // 根据业务逻辑计算成本节约率
  return 12 // 示例数据
})

// 图表配置
const waterQualityTrendOption = ref({})
const waterQualityStandardOption = ref({})
const supplyTrendOption = ref({})
const capacityUtilizationOption = ref({})
const costCompositionOption = ref({})
const unitCostComparisonOption = ref({})
const equipmentStatusOption = ref({})
const failureRateTrendOption = ref({})
const workOrderEfficiencyOption = ref({})
const workOrderCompletionOption = ref({})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取水厂列表
    const factoryRes = await getFactoryList()
    factoryOptions.value = factoryRes.data
    if (factoryOptions.value.length > 0) {
      selectedFactory.value = factoryOptions.value[0].dictValue
    }

    // 获取所有数据
    await fetchAllData()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取所有数据
const fetchAllData = async () => {
  if (!selectedFactory.value) return

  const params = {
    factoryId: selectedFactory.value,
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  }

  try {
    loading.value = true

    const [
      qualityRes,
      standardRateRes,
      supplyRes,
      costRes,
      tasksRes,
      statusRes,
      failureRes,
      efficiencyRes,
      completionRes,
      trendRes,
      utilizationRes,
      compositionRes,
      comparisonRes
    ] = await Promise.all([
      getWaterQualityStatistics(params),
      getWaterQualityStandardRate(params),
      getSupplyStatistics(params),
      getCostStatistics(params),
      getTodoTasks(params),
      getEquipmentStatus(),
      getFailureRateTrend(),
      getWorkOrderEfficiency(),
      getWorkOrderCompletionRate(),
      getTargetTrend(),
      getCapacityUtilization(),
      getCostComposition(),
      getUnitCostComparison()
    ])

    // 更新数据
    Object.assign(waterQualityData, qualityRes.data)
    Object.assign(waterQualityStandardRate, standardRateRes.data)
    Object.assign(supplyData, supplyRes.data)
    Object.assign(costData, costRes.data)
    todoTasks.value = tasksRes.data
    Object.assign(equipmentStatus, statusRes.data)
    Object.assign(failureRateTrend, failureRes.data)
    Object.assign(workOrderEfficiency, efficiencyRes.data)
    Object.assign(workOrderCompletionRate, completionRes.data)
    Object.assign(targetTrend, trendRes.data)
    Object.assign(capacityUtilization, utilizationRes.data)
    Object.assign(costComposition, compositionRes.data)
    Object.assign(unitCostComparison, comparisonRes.data)

    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateCharts = () => {
  // 水质趋势图
  waterQualityTrendOption.value = {
    title: {
      text: '水质趋势图',
      left: 'left',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['pH值', '浊度', '余氯']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1日', '5日', '10日', '15日', '20日', '25日', '30日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: 'pH值',
        type: 'line',
        data: [7.0, 7.1, 7.2, 7.3, 7.2, 7.1, 7.2],
        smooth: true,
        lineStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '浊度',
        type: 'line',
        data: [1.2, 1.0, 0.9, 0.8, 0.7, 0.8, 0.8],
        smooth: true,
        lineStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '余氯',
        type: 'line',
        data: [0.3, 0.35, 0.4, 0.45, 0.4, 0.35, 0.4],
        smooth: true,
        lineStyle: {
          color: '#EE6666'
        }
      }
    ]
  }

  // 水质达标率
  waterQualityStandardOption.value = {
    title: {
      text: '水质达标率',
      left: 'left',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '水质达标率',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: waterQualityStandardRate.qualifiedRate || 95, name: '达标' },
          { value: waterQualityStandardRate.unqualifiedRate || 5, name: '不达标' }
        ],
        color: ['#67C23A', '#F56C6C']
      }
    ]
  }

  // 日供水量趋势
  supplyTrendOption.value = {
    title: {
      text: '日供水量趋势',
      left: 'left',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}<br/>供水量: {c} 万吨'
    },
    xAxis: {
      type: 'category',
      data: targetTrend.dateList || ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
      axisLabel: {
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '万吨',
      min: 0,
      max: 30,
      interval: 5,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [{
      name: '供水量',
      type: 'bar',
      barWidth: '40%',
      data: targetTrend.waterAmountList || [22, 24, 25.5, 23, 26, 27, 24],
      itemStyle: {
        color: function (params) {
          return params.dataIndex === 2 ? '#1890FF' : '#36cfc9';
        },
        borderRadius: [4, 4, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: function (params) {
          return params.dataIndex === 2 ? params.value : '';
        }
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  console.log(capacityUtilization);

  // 产能利用率
  capacityUtilizationOption.value = {
    title: {
      text: '产能利用率',
      left: 'left'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['设计产能', '实际产能']
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: capacityUtilization.dateList
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: '{value} 万吨'
      }
    },
    series: [
      {
        name: '设计产能',
        type: 'line',
        data: capacityUtilization.designedCapacity || [30, 30, 30, 30, 30, 30, 30],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#cccccc'
        }
      },
      {
        name: '实际产能',
        type: 'line',
        data: capacityUtilization.actualCapacity || [24.5, 25, 25.5, 26, 26.5, 26, 25.5],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#1890ff'
        }
      }
    ]
  }

  // 成本构成分析
  costCompositionOption.value = {
    title: {
      text: '成本构成分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: costComposition.costItems || ['电费', '药剂', '人工', '维护']
    },
    series: [
      {
        name: '成本构成',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: costComposition.costPercentages?.map((value, index) => ({
          value,
          name: costComposition.costItems[index]
        })) || [
            { value: 40, name: '电费' },
            { value: 30, name: '药剂' },
            { value: 20, name: '人工' },
            { value: 10, name: '维护' }
          ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  // 单位成本对比
  unitCostComparisonOption.value = {
    title: {
      text: '单位成本对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: unitCostComparison.months || ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: '{value} 元/吨'
      }
    },
    series: [
      {
        name: '单位成本',
        type: 'line',
        data: unitCostComparison.monthlyUnitCosts || [1.28, 1.25, 1.22, 1.23, 1.21, 1.22],
        symbol: 'circle',
        symbolSize: 8,
        smooth: true
      }
    ]
  }

  // 设备运行状态
  equipmentStatusOption.value = {
    title: {
      text: '设备运行状态',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: equipmentStatus.items?.map(item => item.status) || ['正常运行', '维护中', '故障']
    },
    series: [
      {
        name: '设备运行状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: equipmentStatus.items?.map(item => ({
          value: item.count,
          name: item.status
        })) || [
            { value: 80, name: '正常运行' },
            { value: 10, name: '维护中' },
            { value: 10, name: '故障' }
          ]
      }
    ]
  }

  // 设备故障率趋势
  failureRateTrendOption.value = {
    title: {
      text: '设备故障率趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: failureRateTrend.months || ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: '设备故障率',
        type: 'line',
        data: failureRateTrend.rates || [6.5, 5.8, 5.2, 4.9, 5.1, 4.8],
        symbol: 'circle',
        symbolSize: 8,
        smooth: true,
      }
    ]
  }

  // 工单处理效率
  workOrderEfficiencyOption.value = {
    title: {
      text: '工单处理效率',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: workOrderEfficiency.months || ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 10,
      interval: 2,
      axisLabel: {
        formatter: '{value} 小时'
      }
    },
    series: [
      {
        name: '工单处理效率',
        type: 'bar',
        data: workOrderEfficiency.avgHandleTimes || [8.5, 7.8, 7.2, 6.5, 6.0, 5.5],
        itemStyle: {
          color: '#2f97ff'
        }
      }
    ]
  }

  // 工单完成率
  workOrderCompletionOption.value = {
    title: {
      text: '工单完成率',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: workOrderCompletionRate.months || ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      interval: 20,
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: '工单完成率',
        type: 'line',
        data: workOrderCompletionRate.completionRates || [90, 92, 94, 96, 98, 100],
        symbol: 'circle',
        symbolSize: 8,
        smooth: true,
        lineStyle: {
          color: '#1890ff'
        }
      }
    ]
  }
}

// 处理水厂变化
const handleFactoryChange = () => {
  fetchAllData()
}

// 处理日期变化
const handleDateChange = () => {
  fetchAllData()
}

// 处理标签页变化
const handleTabChange = () => {
  // 可以根据需要加载特定标签页的数据
}

// 刷新数据
const refreshData = () => {
  fetchAllData()
}

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '--'
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取状态类名
const getStatusClass = (status) => {
  if (!status) return ''
  const statusMap = {
    '正常': 'status-good',
    '达标': 'status-good',
    '异常': 'status-warning',
    '不达标': 'status-warning'
  }
  return statusMap[status] || ''
}

// 获取压力状态类名
const getPressureStatusClass = (status) => {
  if (!status) return ''
  const statusMap = {
    '稳定': 'status-good',
    '波动': 'status-warning',
    '异常': 'status-danger'
  }
  return statusMap[status] || ''
}

// 获取任务状态类名
const getTaskStatusClass = (status) => {
  if (!status) return ''
  const statusMap = {
    '高效完成': 'status-urgent',
    '完成': 'status-normal',
    '计划性': 'status-planned'
  }
  return statusMap[status] || ''
}

// 获取任务标签类型
const getTaskTagType = (status) => {
  if (!status) return ''
  const statusMap = {
    '高效完成': 'danger',
    '完成': 'success',
    '计划性': 'info'
  }
  return statusMap[status] || ''
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.header-card {
  margin-bottom: 20px;
}

.metric-row {
  margin-bottom: 20px;
}

.metric-card {
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.card-title {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: bold;
}

.card-date {
  color: #999;
  font-size: 12px;
}

/* 指标项样式 */
.metric-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.metric-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.metric-title {
  color: #666;
  font-size: 14px;
}

.metric-range {
  color: #999;
  font-size: 12px;
}

.metric-trend {
  font-size: 12px;
  font-weight: bold;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.metric-footer {
  display: flex;
  justify-content: space-between;
}

.metric-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.status-good {
  color: #67C23A;
  background-color: #f0f9eb;
}

.status-normal {
  color: #409EFF;
  background-color: #ecf5ff;
}

.status-warning {
  color: #E6A23C;
  background-color: #fdf6ec;
}

.status-danger {
  color: #F56C6C;
  background-color: #fef0f0;
}

.status-stable {
  color: #909399;
  background-color: #f4f4f5;
}

/* 任务项样式 */
.task-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.task-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.task-title {
  font-size: 14px;
  font-weight: 500;
}

.task-time {
  color: #999;
  font-size: 12px;
}

.status-urgent .task-title {
  color: #F56C6C;
}

.status-normal .task-title {
  color: #67C23A;
}

.status-planned .task-title {
  color: #409EFF;
}

/* 图表区域 */
.chart-card {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-container {
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.chart-title {
  margin: 0 0 15px;
  color: #333;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}
</style>